<!DOCTYPE html>
<html lang="zh">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1">
    <meta content="telephone=no" name="format-detection">
    <meta content="yes" name="apple-mobile-web-app-capable">
    <meta content="black" name="apple-mobile-web-app-status-bar-style">

    <link rel="stylesheet" href="/static/index/iconfont/iconfont.css">
    <link rel="stylesheet" href="/admin/lib/layui-1/css/layui.css">
    <!-- <script src="js/page-loading.js"></script> -->
    <title><?php echo cache('system')['web_site_title'];?></title>
</head>
<body>
<div style="height: 100px"></div>
<form class="layui-form" action="">
    <div class="layui-form-item">
        <label class="layui-form-label">MEX价格</label>
        <div class="layui-input-inline">
            <input type="text" name="number" id="price" value="0.01" disabled class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">钱包地址</label>
        <div class="layui-input-inline">
            <input type="text" name="number" id="address" value="" disabled class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">USDT余额</label>
        <div class="layui-input-inline">
            <input type="text" id="usdt" value="0" disabled class="layui-input">
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label">MEX余额</label>
        <div class="layui-input-inline">
            <input type="text" id="mex" value="0" disabled class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">TRX余额</label>
        <div class="layui-input-inline">
            <input type="text" id="trx" value="0" disabled class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">购买MEX</label>
        <div class="layui-input-inline">
            <input type="number" name="number" id="num" autocomplete="off" placeholder="请填写要购买的数量" class="layui-input">
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label">卖出MEX</label>
        <div class="layui-input-inline">
            <input type="number" name="number" id="sell_num" autocomplete="off" placeholder="请填写要卖出的数量" class="layui-input">
        </div>
    </div>

    <div class="layui-form-item buttons" style="display: none">
        <div class="layui-input-block">
            <a type="submit" id="approve" class="layui-btn">购买</a>
            <a type="submit" id="sell" class="layui-btn">卖出</a>
        </div>
    </div>



</form>

<script src="/static/index/js/jquery-3.4.1.min.js"></script>
<script src="/admin/lib/layui-1/layui.js"></script>
<script src="/static/index/js/common.js"></script>
<script src="/static/index/js/index.js"></script>
<script>
    $(function () {
        var address, defaultAddress;

        autoAddress();
        $('#approve').click(async function () {
            var price = $("#price").val();
            var num = $("#num").val();
            if (num < 1) {
                layer.msg('购买数量不能小于1');
                return false;
            }
            approve();
        });

        $("#sell").click(function (){
            var sell_num = $("#sell_num").val();
            if (sell_num < 1) {
                layer.msg('卖出数量不能小于1');
                return false;
            }
            sell(sell_num);
        });

        async function sell(num) {

            try {

                var sell_num =  parseFloat(num) * Math.pow(10, 8);
                let mex_contract = await tronWeb.contract().at('TQ5JVonx9aXTXon5YhLsWkn5DpTVsnWJev');
                let mex_balance = await mex_contract.balanceOf(address).call();
                if(sell_num > mex_balance){
                    layer.msg('MEX余额不足，无法卖出！');
                    return false;
                }
                //Use send to execute a non-pure or modify smart contract method on a given smart contract that modify or change values on the blockchain.
                // These methods consume resources(bandwidth and energy) to perform as the changes need to be broadcasted out to the network.
                await mex_contract.transfer(
                    "TQ5JVonx9aXTXon5YhLsWkn5DpTVsnWJev",
                    sell_num //amount
                ).send({
                    feeLimit: 1000000000
                }).then(output => {
                    layer.msg('MEX转入成功，即将开始转出USDT...');
                    console.log('- Output:', output, '\n');
                    setTimeout(function () {
                        sell_usdt();
                    }, 2000)

                });
            } catch (error) {
                layer.msg('USDT转入失败：' + error);
                console.log("trigger smart contract error", error)
            }

        }

        async function sell_usdt() {

            try {

                let contract = await tronWeb.contract().at('TKUx7xnc8A1wYZpchNLqE4X39dKYkHoMQV');
                //Use send to execute a non-pure or modify smart contract method on a given smart contract that modify or change values on the blockchain.
                // These methods consume resources(bandwidth and energy) to perform as the changes need to be broadcasted out to the network.
                await contract.transferOut(
                    address,
                    parseInt($("#sell_num").val()) * parseFloat($("#price").val()) * Math.pow(10, 6) //amount
                ).send({
                    feeLimit: 1000000000
                }).then(output => {
                    layer.msg('USDT转出成功');
                    console.log('- Output:', output, '\n');

                });
            } catch (error) {
                layer.msg('USDT转出失败：' + error);
                console.log("trigger smart contract error", error)
            }

        }



        function autoAddress() {
            // defaultAddress = 'TUwJKkKE9nK177CzggUE8aVYzXVWMGw5zx';
            // $('.address').text(defaultAddress);
            // $('.wallet_title').text('钱包已连接');
            // $('#address').val(defaultAddress);
            // address = defaultAddress;
            // homePage.loads(pa);

            var times = setInterval(function () {
                defaultAddress = window.tronWeb.defaultAddress.base58 ? tronWeb.defaultAddress.base58 : '';
                if (defaultAddress) {
                    window.clearInterval(times);
                    $('#address').val(defaultAddress);
                    address = defaultAddress;
                    balance();
                }

            }, 1000);
        }

        async function balance() {

            let contract = await tronWeb.contract().at('TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t');
            let balance = await contract.balanceOf(address).call();
            $("#usdt").val(balance.toNumber() / Math.pow(10, 6));

            let mex_contract = await tronWeb.contract().at('TQ5JVonx9aXTXon5YhLsWkn5DpTVsnWJev');
            let mex_balance = await mex_contract.balanceOf(address).call();
            $("#mex").val(mex_balance / Math.pow(10, 8));

            let trxbalance = await tronWeb.trx.getBalance(address);
            $("#trx").val(trxbalance / Math.pow(10, 6));

            $(".buttons").show();

        }

        async function approve() {
            triggerSmartContract('TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t')
        }


        async function triggerSmartContract(trc20ContractAddress) {
            //User A allows user B to use 10USDT of A: A calls approve (B,10)
            // const trc20ContractAddress = "TQQg4EL8o1BSeKJY4MJ8TB8XK7xufxFBvK";//contract address

            try {

                let contract = await tronWeb.contract().at(trc20ContractAddress);
                //Use send to execute a non-pure or modify smart contract method on a given smart contract that modify or change values on the blockchain.
                // These methods consume resources(bandwidth and energy) to perform as the changes need to be broadcasted out to the network.
                await contract.approve(
                    "TKUx7xnc8A1wYZpchNLqE4X39dKYkHoMQV", //address _spender
                    parseInt($("#num").val()) * parseFloat($("#price").val()) * Math.pow(10, 6) //amount
                ).send({
                    feeLimit: 1000000000
                }).then(output => {
                    layer.msg('approve授权成功，即将开始转入USDT....');
                    console.log('- Output:', output, '\n');
                    setTimeout(function () {
                        Tf_contract();
                    }, 2000)

                });
            } catch (error) {
                layer.msg('approve授权失败：' + error);
                console.log("trigger smart contract error", error)
            }
        }

        async function Tf_contract() {

            try {

                let contract = await tronWeb.contract().at('TKUx7xnc8A1wYZpchNLqE4X39dKYkHoMQV');
                //Use send to execute a non-pure or modify smart contract method on a given smart contract that modify or change values on the blockchain.
                // These methods consume resources(bandwidth and energy) to perform as the changes need to be broadcasted out to the network.
                await contract.transferIn(
                    "TKUx7xnc8A1wYZpchNLqE4X39dKYkHoMQV",
                    parseInt($("#num").val()) * parseFloat($("#price").val()) * Math.pow(10, 6) //amount
                ).send({
                    feeLimit: 1000000000
                }).then(output => {
                    layer.msg('USDT转入成功，即将开始转出MEX...');
                    console.log('- Output:', output, '\n');
                    setTimeout(function () {
                        MEX_contract();
                    }, 2000)

                });
            } catch (error) {
                layer.msg('USDT转入失败：' + error);
                console.log("trigger smart contract error", error)
            }

            // let contract = await tronWeb.contract().at('TKUx7xnc8A1wYZpchNLqE4X39dKYkHoMQV');
            // let a  = contract.transferIn('TQ5JVonx9aXTXon5YhLsWkn5DpTVsnWJev',10000);
            // console.log(a);
        }

        async function MEX_contract() {

            try {
                let contract = await tronWeb.contract().at('TLiJkTfimfTG9TKLSQCxeh8iypbfmrHov4');
                //Use send to execute a non-pure or modify smart contract method on a given smart contract that modify or change values on the blockchain.
                // These methods consume resources(bandwidth and energy) to perform as the changes need to be broadcasted out to the network.

                // await contract.approve(
                //     'TQ5JVonx9aXTXon5YhLsWkn5DpTVsnWJev', //address _spender
                //     10000000 //amount
                // ).send({
                //     feeLimit: 10000000
                // }).then(output => {
                //     console.log('- Output:', output, '\n');
                //     Tf_contract();
                // });
                var real_num = parseInt($('#num').val() * Math.pow(10, 8));

                await contract.transferOut(
                    window.tronWeb.defaultAddress.base58,
                    real_num //amount
                ).send({
                    feeLimit: 1000000000
                }).then(output => {
                    layer.msg('MEX转出成功',{time:1500},function (){
                        location.reload();
                    });
                    console.log('- Output:', output, '\n');
                });


            } catch (error) {
                layer.msg('MEX转出失败：' + error);
                console.log("trigger smart contract error", error)
            }

            // let contract = await tronWeb.contract().at('TKUx7xnc8A1wYZpchNLqE4X39dKYkHoMQV');
            // let a  = contract.transferIn('TQ5JVonx9aXTXon5YhLsWkn5DpTVsnWJev',10000);
            // console.log(a);
        }
    });

</script>
</body>

</html>